<template>
	<div>
		<!-- 编辑弹框 -->
		<el-dialog v-if="dialogVisible" :model-value="dialogVisible" :show-close="false" :before-close="handleClose" width="70%">
			<template #header="{ titleId, titleClass }">
				<div class="my-header">
					<h4 :id="titleId" :class="titleClass">{{ headerTitle }}</h4>
					<el-button type="danger" plain size="small" class="custom-close-btn" @click="handleSilentClose">
						<el-icon :size="16"><Close /></el-icon>
					</el-button>
				</div>
			</template>
			<el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="120px" class="ruleForm" :size="formSize" status-icon>
				<el-form-item label="标题" prop="title">
					<el-input v-model="form.title" />
				</el-form-item>
				<el-form-item label="详情内容" prop="content">
					<TiptapEditor v-model="form.content" class="editor-container" style="min-height: 500px" />
				</el-form-item>

				<el-form-item label="展示状态" prop="state">
					<el-select v-model="form.state" placeholder="请选择状态">
						<el-option label="展示" :value="1" />
						<el-option label="不展示" :value="2" />
					</el-select>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="handleResetForm(ruleFormRef)">取消</el-button>
					<el-button type="primary" @click="handleSubmitForm(ruleFormRef)">提交</el-button>
				</span>
			</template>
		</el-dialog>

		<el-row>
			<!-- 搜索表单 -->
			<el-col>
				<el-form :inline="true">
					<el-row>
						<el-col>
							<el-form-item label-width="5px">
								<el-input v-model="title" placeholder="请输入标题" />
							</el-form-item>

							<el-form-item label-width="5px">
								<el-button type="primary" :icon="Search" @click="load">查询</el-button>
								<el-button type="warning" :icon="Refresh" @click="handleReset">重置</el-button>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
			</el-col>

			<!-- 操作按钮 -->
			<el-col style="margin-bottom: 10px; display: flex; gap: 10px">
				<div v-permission="'sys:homepage:add'">
					<el-button type="primary" :icon="Plus" size="small" plain @click="handleAdd">新增</el-button>
				</div>

				<div v-permission="'sys:homepage:batch:delete'">
					<el-popconfirm
						confirm-button-text="确定"
						cancel-button-text="取消"
						:icon="InfoFilled"
						icon-color="#626AEF"
						title="确认要批量删除吗？"
						@confirm="handleBatchDel"
						@cancel="load"
					>
						<template #reference>
							<el-button type="danger" :disabled="disabled" :icon="Delete" size="small" plain>批量删除</el-button>
						</template>
					</el-popconfirm>
				</div>

				<div v-permission="'sys:homepage:batch:export'">
					<el-button type="warning" :icon="Download" :disabled="disabled" size="small" plain @click="handleBatchExport">批量导出</el-button>
				</div>
			</el-col>

			<!-- 数据表格 -->
			<el-col>
				<el-table
					:data="tableData"
					style="width: 100%"
					:header-cell-style="{ background: '#eef1f6', color: '#606266' }"
					@selection-change="handleSelectionChange"
				>
					<el-table-column type="selection" width="55" />
					<el-table-column prop="id" label="ID" align="center" sortable />
					<el-table-column prop="title" label="标题" align="center" />
					<el-table-column prop="state" label="状态" align="center">
						<template #default="scope">
							<el-tag
								v-permission="'sys:homepage:update'"
								:type="scope.row.state === 1 ? 'success' : 'danger'"
								style="cursor: pointer"
								@click="handleStateChange(scope.row)"
							>
								{{ scope.row.state === 1 ? '展示中' : '未展示' }}
							</el-tag>
						</template>
					</el-table-column>

					<el-table-column prop="createTime" label="创建时间" align="center" />
					<el-table-column prop="updateTime" label="修改时间" align="center" />

					<el-table-column label="操作" align="center" width="200">
						<template #default="scope">
							<div style="display: flex; justify-content: center; gap: 10px">
								<div v-permission="'sys:homepage:update'">
									<el-button type="primary" :icon="Edit" size="small" @click="handleUpdate(scope.row.id)">编辑</el-button>
								</div>
								<div v-permission="'sys:homepage:delete'">
									<el-popconfirm
										confirm-button-text="确定"
										cancel-button-text="取消"
										:icon="InfoFilled"
										icon-color="#626AEF"
										title="确认要删除吗？"
										@confirm="handleDel(scope.row.id)"
										@cancel="load"
									>
										<template #reference>
											<el-button type="danger" :icon="Delete" size="small">删除</el-button>
										</template>
									</el-popconfirm>
								</div>
							</div>
						</template>
					</el-table-column>
				</el-table>

				<!-- 分页 -->
				<div class="pagination">
					<el-pagination
						:current-page="pageNum"
						:page-size="pageSize"
						:page-sizes="[10, 20, 30, 50]"
						size="small"
						layout="total, sizes, prev, pager, next, jumper"
						:total="Number(total)"
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
					/>
				</div>
			</el-col>
		</el-row>
	</div>
</template>

<script setup>
import { reactive, ref, shallowRef } from 'vue'
import { CircleCloseFilled, Close, Delete, Download, Edit, InfoFilled, Plus, Refresh, Search, Upload, View } from '@element-plus/icons-vue'
import request from '@/utils/request'
import { dayjs, ElMessage, ElMessageBox } from 'element-plus'
import downloadExcel from '@/utils/downloads'
import 'md-editor-v3/lib/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'
import router from '@/router'
import UploadImage from '@/components/upload/upload-image/index.vue'
import TiptapEditor from '@/components/tiptap/TiptapEditor.vue'

const headerTitle = ref()
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const tableData = ref([])
const multipleSelection = ref([])
const disabled = ref(true)
const dialogVisible = ref(false)
const name = ref('')
const formSize = ref('default')
const ruleFormRef = ref()
const $route = router
const title = ref('')

const form = reactive({
	id: undefined,
	title: '',
	content: '',
	state: 2,
	createTime: undefined,
	updateTime: undefined
})

// 表单校验规则
const rules = reactive({
	content: [{ required: true, message: '详情内容不能为空', trigger: 'blur' }],
	state: [{ required: true, message: '请选择展示状态', trigger: 'change' }]
})

//新增方法
const handleAdd = async () => {
	headerTitle.value = reactive('新增数据')
	dialogVisible.value = true
}

const handleStateChange = async row => {
	try {
		await ElMessageBox.confirm(`确定要将状态修改为 ${row.state === 1 ? '不展示' : '展示'} 吗？`, '状态修改确认', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning'
		})

		const newState = row.state === 1 ? 2 : 1

		// 仅在设置为展示中时检查
		if (newState === 1) {
			const res = await request.get('/homepage/exists', {
				params: { excludeId: row.id }
			})
			if (res.data) {
				ElMessage.error('已有其他首页处于展示中，请先取消后再设置！')
				return
			}
		}

		await request.put(`/homepage/${row.id}`, { state: newState })
		ElMessage.success('状态修改成功')
		await load()
	} catch (error) {
		if (error !== 'cancel') {
			ElMessage.info('已取消修改')
		}
	}
}

// 修改方法
const handleUpdate = async id => {
	dialogVisible.value = true
	headerTitle.value = reactive('编辑数据')
	const res = await request.get(`/homepage/${id}`)
	Object.assign(form, res.data)
}

const handleUpdate1 = async id => {
	$route.push(`/comment?id=${id}`)
}

const handleSilentClose = () => {
	handleResetForm(ruleFormRef.value)
	dialogVisible.value = false
}

// 单个删除方法
const handleDel = async id => {
	await request.delete(`/homepage/${id}`)
	ElMessage({
		showClose: true,
		message: '删除成功',
		type: 'success'
	})
	await load()
}

// 批量删除方法
const handleBatchDel = async () => {
	const ids = []
	multipleSelection.value.forEach(row => {
		ids.push(row.id)
	})
	await request.delete(`/homepage/batch/${ids}`)
	ElMessage({
		showClose: true,
		message: '批量删除成功',
		type: 'success'
	})
	await load()
}

// 分页查询方法（初始化方法，页面加载成功以后就调用的方法）
const load = async () => {
	const res = await request.get('/homepage/page', {
		params: {
			pageNum: pageNum.value,
			pageSize: pageSize.value,
			title: title.value
		}
	})
	pageNum.value = res.data.current
	pageSize.value = res.data.size
	total.value = res.data.total
	tableData.value = res.data.records
}

// 加载页面初始化调用load方法
load()

// 清空查询数据重置方法
const handleReset = () => {
	title.value = ''
	load()
}

// 修改每页展示的数据量方法
const handleSizeChange = size => {
	pageSize.value = size
	load()
}

// 翻页方法
const handleCurrentChange = current => {
	pageNum.value = current
	load()
}

// 多选按钮处理方法
const handleSelectionChange = val => {
	multipleSelection.value = val
	disabled.value = val.length === 0
}

// 关闭弹框提示方法
const handleClose = done => {
	ElMessageBox.confirm('确定关闭窗口?')
		.then(() => {
			handleResetForm(ruleFormRef.value)
		})
		.then(() => {
			done()
		})
		.catch(() => {
			// catch error
		})
}

// 提交表单校验方法
const handleSubmitForm = async formEl => {
	if (!formEl) {
		return
	}
	await formEl.validate(async (valid, fields) => {
		if (valid) {
			// 检查是否设置为展示中
			if (form.state === 1) {
				// 调用接口检查是否存在其他展示中的条目（排除当前编辑的ID）
				const res = await request.get('/homepage/exists', {
					params: { excludeId: form.id || null }
				})
				if (res.data) {
					ElMessage.error('已有其他首页处于展示中，请先取消后再设置！')
					return
				}
			}

			const method = form.id ? 'put' : 'post'
			const url = form.id ? `/homepage/${form.id}` : '/homepage'

			if (!form.id) {
				form.uid = 1
			} // 新增时添加UID（根据实际需求）

			await request({ method, url, data: form })
			ElMessage.success('操作成功')
			await handleResetForm(formEl)
			await load()
		} else {
			console.log('表单校验未通过', fields)
		}
	})
}

// 批量导入读数据写到后端数据库中
const beforeBatchUpload = async file => {
	let fd = new FormData()
	fd.append('file', file)
	await request.post('/homepage/page/batch/upload', fd, {
		headers: {
			'Content-Type': 'multipart/form-data'
		}
	})
	ElMessage({
		showClose: true,
		message: '上传成功',
		type: 'success'
	})
	await load()
}

// 批量导出方法
const handleBatchExport = async () => {
	const ids = multipleSelection.value.map(row => row.id)
	const res = await request(
		{
			url: `/homepage/batch/export/${ids}`,
			method: 'get',
			responseType: 'blob'
		} //在请求中加上这一行，特别重要
	)
	downloadExcel(res, '导出数据表')
}

// 取消弹框方法
const handleResetForm = async formEl => {
	if (!formEl) {
		return
	}
	formEl.resetFields()

	Object.assign(form, {
		id: undefined,
		name: undefined,
		img: undefined,
		content: undefined,
		createTime: undefined
	})
	// formEl.clearValidate("img")
	dialogVisible.value = false
	await load()
}

// 文件上传方法
const uploadimg = async file => {
	let fd = new FormData()
	fd.append('file', file)
	const res = await request.post('/file/upload', fd, {
		headers: {
			'Content-Type': 'multipart/form-data'
		}
	})
	ElMessage({
		showClose: true,
		message: '上传成功',
		type: 'success'
	})
	form.img = res.data
	ruleFormRef.value.clearValidate('img')
}

// 文件下载
const dowload = async url => {
	window.open(url)
}
// 富文本文件上传
const onUploadImg = async (files, callback) => {
	let i = 0
	const res = await Promise.all(
		files.map(file => {
			if (i > 0) {
				return false
			}
			return new Promise((rev, rej) => {
				const formdata = new FormData()
				formdata.append('file', file)

				request
					.post('/file/upload', formdata, {
						headers: {
							'Content-Type': 'multipart/form-data'
						}
					})
					.then(res => {
						i++
						rev(res.data)
					})
					.catch(error => rej(error))
			})
		})
	)
	callback(res)
}
</script>

<style scoped lang="scss">
.el-form--inline .el-form-item {
	margin-right: 10px;
}

.form_header {
	background-color: #666666;
}

.pagination {
	margin-top: 10px;
}

.my-header {
	display: flex;
	flex-direction: row;
	justify-content: space-between;
}

.custom-close-btn {
	border: none !important;
	padding: 5px !important;
	transition: all 0.3s;

	&:hover {
		transform: rotate(90deg);
		color: #ff4d4f !important;
		background: rgba(255, 77, 79, 0.1) !important;
	}
}

.content-preview {
	max-height: 100px;
	overflow: auto;
}
.content-preview img {
	max-width: 100%;
}
</style>
